﻿<%@ WebHandler Language="C#" Class="RbContainerWorkflowConfirmHandler" %>

/*Description: 热表工艺确认处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20240712
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using NPOI.SS.UserModel;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using BusinessRule.Common;

public class RbContainerWorkflowConfirmHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    uLMSContainerBusiness containerBusiness = new uLMSContainerBusiness();
    string fileBasePath = System.Configuration.ConfigurationManager.AppSettings["ImportPath"].ToString();//导入临时路径

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetWorkflowConfirmData": //获取待工艺确认的批次数据
                    GetWorkflowConfirmData(context);
                    break;
                case "SaveWorkflowConfirm": //保存工艺确认
                    SaveWorkflowConfirm(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 保存工艺确认
    /// </summary>
    /// <param name="context"></param>
    public void SaveWorkflowConfirm(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "确认成功" };
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        string strLevel = string.Empty;
        DataTable levelAttributes = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID);
        DataRow[] datarows = levelAttributes.Select("USERATTRIBUTENAME='默认层级'");
        if (datarows.Length > 0)
        {
            strLevel = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }
        ServerHostInfo host = new ServerHostInfo();
        host.UserName = m_UserInfo.APIUserName;
        host.Password = m_UserInfo.APIPassword;
        string sql = @"SELECT wb.workflowname,w.workflowrevision,ws.workflowstepname,ws.workflowstepid
                         FROM containercurrentinfo c 
                         LEFT JOIN container cc ON cc.containerid = c.containerid
                         LEFT JOIN workflow w ON w.workflowid = cc.mfgworkflowid
                         LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                         LEFT JOIN workflowstep ws ON ws.workflowid = cc.mfgworkflowid
                         WHERE c.containerid = '{0}' AND c.workflowstepname = '工艺确认' AND c.containerstatus = 1 AND c.isinstore = -1
                         AND ws.sequence = 1";
        bool res = true;
        string msg = string.Empty;
        foreach (DataRow item in dtContainer.Rows)
        {
            DataTable dtWorkflow = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, item["containerid"].ToString()));
            if (dtWorkflow.Rows.Count == 0)
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}未存在工艺确认，请刷新页面", item["containername"].ToString());
                break;
            }
            DataRow drW = dtWorkflow.Rows[0];
            ContainerStartInfo para = new ContainerStartInfo()
            {
                ContainerName = item["containername"].ToString(),
                AttributeName = "工艺确认",
                ServerHostInfo = host,
                Level = strLevel,
                attributeValue = string.Format("{0}&{1}", m_UserInfo.EmployeeID, DateTime.Now.ToString())
            };
            commonBusiness.SetUserAttribute(para);//更新批次的工艺确认属性
            //移动批次
            res = containerBusiness.ContainerMoveNonStd(host, item["containername"].ToString(), drW["workflowname"].ToString(), drW["workflowrevision"].ToString(), drW["workflowstepname"].ToString(), m_UserInfo.EmployeeName, "", ref msg);
            if (!res)
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}移动报错，原因：", item["containername"].ToString(), msg);
                break;
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取待工艺确认的批次数据
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkflowConfirmData(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.containername,c.containerid,c.qty,c.workflowstepname,c.mfgordername 
                         FROM containercurrentinfo c 
                         WHERE c.workflowstepname = '工艺确认' AND c.containerstatus = 1 AND c.isinstore = -1 AND c.originalfactoryid = '{0}'",m_UserInfo.FactoryID);
        //查询批次
        if (!string.IsNullOrWhiteSpace(context.Request["containerName"].ToString()))
        {
            sql.AppendFormat(" AND c.containername like '%{0}%'", context.Request["containerName"].ToString());
        }
        //查询件号
        if (!string.IsNullOrWhiteSpace(context.Request["productName"].ToString()))
        {
            sql.AppendFormat(" AND c.productname like '%{0}%'", context.Request["productName"].ToString());
        }
        //查询订单号
        if (!string.IsNullOrWhiteSpace(context.Request["mfgOrderName"].ToString()))
        {
            sql.AppendFormat(" AND c.mfgordername like '%{0}%'", context.Request["mfgOrderName"].ToString());
        }
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(context.Request["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(context.Request["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}